<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Libraries\ImageLib;
use App\Models\Link;
use App\Models\Linktag;
use Illuminate\Http\Request;

class LinkController extends Controller
{
    public function __construct()
    {
        $this->middleware('grant:link');
    }

    /**
     * 添加链接
     */
    public function postInsert(Request $request)
    {
        $name = safe($request->input('name'), 50);
        $url = safe($request->input('url'), 100);
        $tag_id = $request->input('tag_id');

        $link = new Link;
        $link->name = $name;
        $link->url = $url;
        $link->status = 1;
        if ($link->save()) {
            is_array($tag_id) and $link->tags()->sync($tag_id);
        }
        $link->tags();
        return $this->response($link);
    }

    /**
     * 编辑链接
     */
    public function postUpdate(Request $request)
    {
        $id = intval($request->input('id'));
        $name = safe($request->input('name'), 50);
        $url = safe($request->input('url'), 100);
        $tag_ids = $request->input('tag_id');

        $link = Link::find($id);
        $link->name = $name;
        $link->url = $url;
        if ($link->save()) {
            $link->tags()->sync(empty($tag_ids) ? [] : $tag_ids);
        }
        $link->tags;
        return $this->response($link);
    }

    /**
     * 上传图片
     */
    public function postUploadPic1(Request $request)
    {
        $id = intval($request->input('id'));
        $file = $_FILES['pic1'];
        $width = intval($request->input('width'));
        $height = intval($request->input('height'));

        $errorCode = $file['error'];
        if ($errorCode !== UPLOAD_ERR_OK) {
            return $this->error($errorCode);
        }

        $type = exif_imagetype($file['tmp_name']);
        if ($type === false) {
            return $this->error('无效的图片文件');
        }
        if (!in_array($type, [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG])) {
            return $this->error('无效的图片格式');
        }

        $target_path = 'upload/' . date('Y/m/d/');
        $targetPath = public_path() . DIRECTORY_SEPARATOR . $target_path;
        if (!is_dir($targetPath)) {
            if (!mkdir($targetPath, 0777, 1)) {
                return $this->error('无法建立上传目录');
            }
        }

        $new_filename = uniqid(mt_rand()) . image_type_to_extension($type);
        $result = move_uploaded_file($file['tmp_name'], $targetPath . $new_filename);
        if ($result === false) {
            return $this->error('保存文件失败');
        }

        $config = [
            'image_library' => 'gd2',
            'source_image' => $targetPath . $new_filename,
            'new_image' => getThumb($targetPath . $new_filename),
            'maintain_ratio' => true,
            'width' => $width,
            'height' => $height,
        ];
        $image_lib = new ImageLib($config);
        if (!$image_lib->resize()) {
            return $this->error($image_lib->display_errors());
        }

        $image = $target_path . $new_filename;
        $link = Link::find($id);
        file_exists($link->pic1) and unlink($link->pic1);
        $thumb = getThumb($link->pic1);
        file_exists($thumb) and unlink($thumb);
        $link->pic1 = $image;
        $link->save();
        return $this->response(asset($image));
    }

    /**
     * 删除链接
     */
    public function postDelete(Request $request)
    {
        $ids = explode('|', $request->input('ids'));
        foreach ($ids as $id) {
            $link = Link::find($id);
            file_exists($link->pic1) and unlink($link->pic1);
            $thumb = getThumb($link->pic1);
            file_exists($thumb) and unlink($thumb);
            $link->tags()->sync([]);
            $link->delete();
        }
        return $this->response('ok');
    }

    /**
     * 增加标签
     */
    public function postAddTag(Request $request)
    {
        $tag = safe($request->input('tag'), 50);
        if (Linktag::where('tag', $tag)->count()) {
            return $this->error('标签名重复');
        }
        $linktag = new Linktag;
        $linktag->tag = $tag;
        $linktag->save();
        return $this->response($linktag);
    }

    /**
     * 编辑标签
     */
    public function postEditTag(Request $request)
    {
        $id = intval($request->input('id'));
        $tag = safe($request->input('tag'), 50);
        $linktag = Linktag::find($id);
        if ($linktag->tag != $tag) {
            if (Linktag::where('tag', $tag)->count()) {
                return $this->error('标签名重复');
            }
            $linktag->tag = $tag;
        }
        $linktag->save();
        return $this->response($linktag);
    }

    /**
     * 删除标签
     */
    public function postDelTag(Request $request)
    {
        $id = intval($request->input('id'));
        $linktag = Linktag::find($id);
        $linktag->links()->sync([]);
        $linktag->delete();
        return $this->response('ok');
    }

}
